package cn.weekimwee.firstlineofcodeforkotlin.unit9.network

import android.util.Log
import com.orhanobut.logger.Logger
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * 书上的网络请求，在此替换为当前用的比较广的retrofit+rxjava
 * 版本是 rxjava2 和 retrofit2
 * Created by Wee Kim Wee on 2018/4/8.
 */
object HttpManager {
    private const val baseURL = "https://www.apiopen.top/"
    private var retrofit: Retrofit

    init {
        val httpLoggingInterceptor = HttpLoggingInterceptor({ message ->
            if (message.startsWith("{") && message.endsWith("}")) {
                Logger.json(message)
            } else {
                Log.e("FirstLineOfCode", "|$message")
            }
        }).apply {
            level = HttpLoggingInterceptor.Level.BODY
        }
        val okHttpClient = OkHttpClient.Builder()
                .readTimeout(120000, TimeUnit.MILLISECONDS)
                .addInterceptor(httpLoggingInterceptor)
                .retryOnConnectionFailure(true)
                .build()
        retrofit = Retrofit.Builder()
                .baseUrl(baseURL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
    }

    val somethingService: SomethingService by lazy { retrofit.create(SomethingService::class.java) }
}